<script type="text/javascript">

function safeImageData(canvasContext, x,y,w,h){
	var imageData=null
	try {
	  try { 
	    imageData=canvasContext.getImageData(x,y,w,h);
	  } catch (e) {
        // run chrome as " /opt/chrome-linux/chrome --allow-file-access-from-files " to be ok

	    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	    imageData=canvasContext.getImageData(x,y,w,h);
	  } 						 
	} catch (e) {
	  throw new Error("unable to access image data: " + e)
	} 
	return imageData
}
function getRgb(imageData, x,y){
	idx = (y*imageData.width+x)*4
	arr = imageData.data
	return [ arr[idx], arr[idx+1], arr[idx+2] ]
}
function rgb2gray(rgb){
//    var [ra,ga,ba]=rgb
//    return Math.round((ra+ga+ba)/3)
    return Math.round((rgb[0]+rgb[1]+rgb[2])/3)
}
function grayVal(imageData, x,y){
	idx = (y*imageData.width+x)*4
	arr = imageData.data
	return rgb2gray([ arr[idx], arr[idx+1], arr[idx+2] ])
}
function setRgb(imageData, x,y, rgbTuple){
	arr = imageData.data
	idx = (y*imageData.width+x)*4
	arr[idx] = rgbTuple[0]
	arr[idx+1] = rgbTuple[1]
	arr[idx+2] = rgbTuple[2]
	arr[idx+3] = 255
}
function colorDiff(a, b){
//	var [ra,ga,ba]=rgb1
//	var [rb,gb,bb]=rgb2
//	return Math.abs(ra-rb)+Math.abs(ga-gb)+Math.abs(ba-bb)
    return Math.abs(a[0]-b[0]) + Math.abs(a[1]-b[1]) + Math.abs(a[2]-b[2])
}
function rgbAdd(a,b){
//	var [ra,ga,ba]=a
//	var [rb,gb,bb]=b
//	return [ra+rb, ga+gb, ba+bb]
    return [a[0]+b[0], a[1]+b[1], a[2]+b[2]]
}
function rgbDiv(a,d){
//	var [ra,ga,ba]=a
//	return [ra/d, ga/d, ba/d]
    return [a[0]/d, a[1]/d, a[2]/d]
}
function rgbToCss(rgb){
//	var [ra,ga,ba]=rgb
//	c=(256*Math.round(ra)+Math.round(ga))*256 + Math.round(ba)
    c=(256*Math.round(rgb[0])+Math.round(rgb[1]))*256 + Math.round(rgb[2])
	return '#'+c.toString(16)
}

function pointBorder(p){
	//var [x,y]=p
    var x = p[0]
    var y = p[1]
	pa = [[x-1,y],[x-1,y-1],[x,y-1],[x+1,y-1],
		[x+1,y],[x+1,y+1],[x,y+1],[x-1,y+1]]
	ret = new PointSet()
	for( i in pa ){
		pb = pa[i]
		ret.add(pb)
	}
	return ret
}

</script>

<script type="text/javascript">

function imageData2GrayFun(imageData){
    var data = new Array()
    for( var x = 0; x<imageData.width; x++ ){
        data[x] = new Array()
        for( var y=0; y<imageData.height; y++ ){
            data[x][y] = grayVal(imageData, x, y)
        }
    }
    return function(px,py){
        if( px<0 || py<0 || px>=imageData.width || py>=imageData.height ){
            return NaN
        }
        return data[px][py]
    }
}

function graySumDiff(grayFun, p, radius, radians){
    cosa = Math.cos(radians)
    sina = Math.sin(radians)
    count1=0
    sum1=0
    count2=0
    sum2=0
    for( dx = -radius; dx <= radius; dx++ ){
        for( dy = -radius; dy <= radius; dy++ ){
            if( dx*dx + dy*dy <= radius*radius ){
                gray = grayFun(p[0]+dx, p[1]+dy)
                if( !isNaN(gray) ){
                    //alert(p+" "+dx+" "+dy+ " "+gray+" counts "+count1+" "+count2 + " radians "+radians+" dline="
                    //                + (y*cosa - x*sina)+" cos="+cosa+" sin="+sina)
                    if( dy*cosa > dx*sina ){
                        count1 ++
                        sum1 += gray
                    }
                    if( dy*cosa < dx*sina ){
                        count2 ++
                        sum2 += gray
                    }
                }
            }
        }
    }
    //alert(p+" "+radians+ " "+sum1+" "+count1+" "+sum2+" "+count2+ "    "+(sum1/count1 - sum2/count2))
    if( count1==0 || count2==0 ){
        return NaN
    }
    return sum1/count1 - sum2/count2
}

function graySummDiffMaxAround(grayFun, p, radius){
    mx = 0
    for( grad = 0; grad < 180; grad += 30 ){
        v = Math.abs( graySumDiff(grayFun,  p, radius, grad / 180 * Math.PI) )
        if( !isNaN(v) ){
            if( mx < v ){
                mx = v
            }
        }
    }
    //alert("mx="+mx)
    return Math.round(mx)
}

function PointSet(){
	this.data = new Array()
	this.add = function(point){
		this.data[ point.join(',') ] = point
	}
	this.contains = function(point){
		return point.join(',') in this.data
	}
	this.remove = function(point){
		delete this.data[point.join(',')]
	}
	this.foreach = function(func){
		for( pj in this.data ){
			func(this.data[pj])
		}
	}
}

function inField(diffAroundField, x,y){
	return x>=0 && x<diffAroundField.length
		&& y>=0 && y<diffAroundField[x].length
}
function isBorder(diffAroundField, x,y){
	var v0 = diffAroundField[x][y]
	var cmore=0
	var cless=0
	for( dx=-1; dx<=1; dx++ ){
		for( dy=-1; dy<=1; dy++ ){
			if( inField(diffAroundField, x+dx, y+dy) ){
				var v = diffAroundField[x+dx][y+dy]
				if( v>v0 ) cmore++
				if( v<v0 ) cless++
			}
		}
	}
	//return (cless>cmore)
	return cmore<2 && cless>2
}


function paintMaxSumDiffAround(){
    var drawingCanvas = document.getElementById('myDrawing');
    if(drawingCanvas.getContext) {
        var context = drawingCanvas.getContext('2d');

        var myImage = new Image();
        myImage.onload = function() {
            context.drawImage(myImage, 0, 0, myDrawing.width, myDrawing.height);
            imageData = safeImageData(context,0, 0, myDrawing.width, myDrawing.height)
            grayFun = imageData2GrayFun(imageData)
            //alert(grayFun(20,30))
		 diffAroundField = new Array() // [x][y] 
            for( x=0; x<imageData.width; x++ ){
			diffAroundField[x] = new Array()
                for( y=0; y<imageData.height; y++ ){
                    g = graySummDiffMaxAround(grayFun, [x,y], 5)
				diffAroundField[x][y] = g
/*
                    if( y==70 ){
                      log = document.getElementById('logArea')
                      log.value = x + " of "+imageData.width + " g="+g  +"\n"+log.value
                      context.fillStyle = '#0000ff'
                    }else{
                        context.fillStyle = rgbToCss([g,g,g])
                    }

                    if( g<10 ){
                        context.fillStyle = '#000000'
                    }else{
                        context.fillStyle = '#ffffff'
                    }

                    context.fillRect(x, y, 1,1)
*/
                }
            }
		alert("diffAroundField len = "+diffAroundField.length)
            for( x=0; x<imageData.width; x++ ){
                for( y=0; y<imageData.height; y++ ){
				if( isBorder(diffAroundField, x, y) ){
					context.fillStyle = '#0000ff'
					context.fillRect(x, y, 1,1)
				}
			}
		 }
        }
        //myImage.src = "3apples.jpeg";
	myImage.src = document.getElementById('i1').src
    }
}


function tests(){
	try{
	c1=[0,0,0]
	c2=[1,2,3]
	cs=rgbAdd(c1,c2)
	if( cs.join(',')!="1,2,3" ){
		alert('test fail 1: '+cs)
	}

	ps = new PointSet()
	ps.add([2,3])
	if( ps.contains([2,4]) ){
		alert('test fail PointSet1')
	}
	if( !ps.contains([2,3]) ){
		alert('test fail PointSet2')
	}
	ps.remove([2,3])
	if( ps.contains([2,3]) ){
		alert('test fail PointSet3')
	}
	ps.add([5,1])
	ps.add([5,2])
	ysum=0
	ps.foreach( function(p){ ysum += p[1] } )
	if( ysum!=3 ){
		alert('test fail PointSet4 ysum='+ysum)
	}

	pointBorder([10,20]).foreach(function(b){
		if( b.length!=2 ){
			alert('test fail 2: '+b+' type '+(typeof b))
		}
	});

	if( rgbToCss([255,255,0]).toUpperCase()!='#FFFF00' ){
		alert('test fail rgbToCss([255,255,0]) = '+rgbToCss([255,255,0]) )
	}
  }catch(e){
	alert('test fail e: '+e)
  }
}
tests()

</script>

<!--img id='i1' src='3apples.jpeg'-->
<img id='i1' src='roadsign.svg.png'>

canvas
<!--canvas id="myDrawing" width="233" height="217" style='border: solid black 1px'-->
<canvas id="myDrawing" width="320" height="320" style='border: solid black 1px'>
<p>Your browser doesn't support canvas.</p>
</canvas>
<hr>

<!--button onclick='canv()'>Start canv</button-->
<button onclick='startPaintReg()'>startPaintReg</button>
<input id='pauseFlag' type=checkbox> pause
<button onclick='diffTrend()'>diffTrend</button>

<button onclick='paintMaxSumDiffAround()'>max-sum-diff-around</button>

<textarea id='logArea' rows=10 cols=40>log
</textarea>


